/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.mobiubiq.directory.client.frame;

import org.kalmeo.kuix.core.Kuix;
import org.kalmeo.kuix.widget.Desktop;
import org.kalmeo.kuix.widget.ListItem;
import org.kalmeo.kuix.widget.Widget;
import org.kalmeo.util.frame.Frame;
import org.kalmeo.util.frame.FrameHandler;
import org.mobiubiq.directory.client.KuixClient;
import org.mobiubiq.directory.client.data.Service;
import org.mobiubiq.directory.client.data.ServiceSettingsRecordStore;
import org.mobiubiq.directory.client.data.ServicesDataProvider;
import org.mobiubiq.directory.client.frame.service.ServiceFrameFactory;
import org.mobiubiq.directory.client.frame.service.ServiceSettingsFrame;
import org.mobiubiq.directory.client.object.AbstractObject;

/**
 *
 * @author Marnix Renne
 */
public class Services extends DataProviderBaseFrame {
    public Services(AbstractObject object) {
        super("services.xml", null);
        setDataProvider(new ServicesDataProvider(object, this));
    }

    public boolean onMessage(Object identifier, Object[] arguments) {
        boolean eventNotProcessed = super.onMessage(identifier, arguments);
        if (eventNotProcessed) {
            if ("open".equals(identifier)) {
                ListItem item = (ListItem) arguments[0];
                Service service = (Service) item.getDataProvider();
                Frame frame = null;
                if(!settingsAreSet(service)) {
                    frame = new ServiceSettingsFrame(service);
                } else {
                    frame = ServiceFrameFactory.getServiceFrame(service);
                }
                KuixClient.debug("Connecting to service: " + service.getId());
                FrameHandler handler = Kuix.getFrameHandler();
                //handler.removeFrame(this);
                handler.pushFrame(frame);
                return false;
            }
        }
            // event processed by super-class
            return false;
    }

    public void dataLoaded() {
        Desktop desktop = Kuix.getCanvas().getDesktop();
        Widget w = desktop.getWidget("waitPlaceHolder");
        w.setVisible(false);
        
        w = desktop.getWidget("servicesContainer");
        w.setVisible(true);
    }
    
    public void error(Exception e) {
        Kuix.alert(e);
        onMessage("back", null);
    }

    private boolean settingsAreSet(Service service) {
        if(service.getSettings() != null && service.getSettings().size() > 0) {
            if(ServiceSettingsRecordStore.getSettings(service) != null) {
                return true;
            } else {
                return false;
            }
        }
        return true;
    }
    
}
